// pages/setAddress/setAddress.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: '',
    // customItem: '请选择',
    addressMsg: {},
    addressId: null, //当前地址项Id
    userName: '',
    userId: '',
    phone: '',
    region: ['请选择所在省市区'],
    address: '',
    post: '',
    checked: false, //是否是默认地址
    nameIstrue: '', //判断姓名校验
    phoneIstrue: '', //判断电话校验
    isDefault: 0,
  },
  bindRegionChange: function(e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },

  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
    if (event.detail == false) {
      this.setData({
        checked: 0
      });
    } else {
      this.setData({
        checked: 1
      });
    }

  },
  choBtn(e) {
    let that = this


    wx.chooseLocation({
      success: function(res) {
        console.log(res);

        //分割省市区
        if (res.address) {
          let adr = res.address
          let area = []
          let detail = ''
          let indexA1 = adr.indexOf("自治区")
          let indexA2 = adr.indexOf("省")
          let indexB1 = adr.indexOf("市")
          let indexB2 = adr.indexOf("地区")
          let indexB3 = adr.indexOf("自治州")
          let indexC1 = adr.indexOf("区")
          let indexC2 = adr.indexOf("县")

          //第一级
          if (indexA1 != -1) { //自治区
            area.push(adr.substring(0, indexA1 + 3))
            console.log(area)
          } else if (indexA2 != -1) { //省
            area.push(adr.substring(0, indexA2 + 1))
            console.log(area)
          } else if (indexA1 == -1 && indexA2 == -1) { //非正常选择情况
            detail = adr
            console.log(detail)
          }

          //第二级
          if (indexA1 != -1 || indexA2 != -1) { //有省级信息才往下执行
            if (indexB1 != -1) { //市
              // area.push(adr.substring(0, indexB1 + 1))

              if (indexA1 != -1) { //自治区 市
                area.push(adr.substring(indexA1 + 3, indexB1 + 1))
              } else if (indexA2 != -1) { //省 市
                area.push(adr.substring(indexA2 + 1, indexB1 + 1))
              }
              console.log(area)
            } else if (indexB2 != -1) { //地区
              // area.push(adr.substring(0, indexB2 + 2))
              // console.log(area)
              if (indexA1 != -1) { //自治区 地区
                area.push(adr.substring(indexA1 + 3, indexB2 + 2))
              } else if (indexA2 != -1) { //省 地区
                area.push(adr.substring(indexA2 + 1, indexB2 + 2))
              }
              console.log(area)
            } else if (indexB3 != -1) { //自治州
              // area.push(adr.substring(0, indexB2 + 2))
              // console.log(area)
              if (indexA1 != -1) { //自治区 自治州
                area.push(adr.substring(indexA1 + 3, indexB3 + 3))
              } else if (indexA2 != -1) { //省 自治州
                area.push(adr.substring(indexA2 + 1, indexB3 + 3))
              }
              console.log(area)
            }

            //第三级
            if (indexC1 != -1) { //区
              // area.push(adr.substring(0, indexC1 + 1))
              if (indexB1 != -1) { //市 区
                area.push(adr.substring(indexB1 + 1, indexC1 + 1))
              } else if (indexB2 != -1) { //地区 区
                area.push(adr.substring(indexB2 + 2, indexC1 + 1))
              } else if (indexB3 != -1) { //自治州 区
                area.push(adr.substring(indexB3 + 2, indexC1 + 1))
              }
              detail = adr.substring(indexC1 + 1, adr.length) + ' ' + res.name
              console.log(area, detail)
            } else if (indexC2 != -1) { //县
              // area.push(adr.substring(0, indexC2 + 1))
              if (indexB1 != -1) { //市 县
                area.push(adr.substring(indexB1 + 1, indexC2 + 1))
              } else if (indexB2 != -1) { //地区 县
                area.push(adr.substring(indexB2 + 2, indexC2 + 1))
              } else if (indexB2 != -1) { //自治州 县
                area.push(adr.substring(indexB3 + 2, indexC2 + 1))
              }
              console.log(adr.substring(indexC2 + 1, adr.length))
              detail = adr.substring(indexC2 + 1, adr.length) + ' ' + res.name
              console.log(area, detail)
            }
            that.setData({ //定位地址输出到data
              region: area,
              address: detail
            })
          } else { //无省市信息
            that.setData({ //定位地址输出到data
              address: detail
            })
          }


          console.log(adr.substring(indexC2 + 1, adr.length))
        }

      },
      fail(res) {
        console.log('fail')
        wx.getSetting({
          success(res) {
            console.log(res.authSetting)
            if (!res.authSetting['scope.userLocation']) {
              console.log('执行里')
              wx.showModal({
                title: '是否进行权限设置?',
                content: '选择地址功能需要获取您的地理位置',
                success(res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                    wx.openSetting({
                      success(res) {
                        console.log(res.authSetting)
                      }
                    })

                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })



            } else {
              console.log('执行外')
            }
          },
          fail(res) {
            console.log('功能未授权，无法使用')
          }
        })

      }
    })

    // wx.getLocation({
    //   type: 'gcj02', //返回可以用于wx.openLocation的经纬度
    //   success(res) {
    //     const latitude = res.latitude
    //     const longitude = res.longitude
    //     wx.openLocation({
    //       latitude,
    //       longitude,
    //       scale: 18
    //     })
    //   }
    // })
  },
  changeName(e) { //输入时改变姓名

    this.setData({
      userName: e.detail
    })
    console.log(this.data.userName)
  },

  changePhone(e) { //输入时改变电话

    this.setData({
      phone: e.detail
    })
    console.log(this.data.phone)
  },
  changeAdd(e) { //输入时改变详细地址

    this.setData({
      address: e.detail
    })
    console.log(this.data.address)
  },
  changeMail(e) { //输入时改变邮箱

    this.setData({
      post: e.detail
    })
    console.log(this.data.post)
  },

  nameBlur(e) { //姓名栏失去焦点
    if (/^[\u4E00-\u9FA5A-Za-z0-9]{2,20}/.test(this.data.userName)) { //校验
      this.setData({
        nameIstrue: ''
      })
    } else {
      this.setData({
        nameIstrue: '请输入长度2-20的姓名，且不能有特殊符号'
      })
    }
    console.log(this.data.nameIstrue)
  },
  phoneBlur(e) { //电话栏失去焦点
    if (/^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\d{8}$/.test(this.data.phone) || /^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/.test(this.data.phone)) { //校验
      this.setData({
        phoneIstrue: ''
      })
    } else {
      this.setData({
        phoneIstrue: '请输入正确的手机号'
      })
    }
  },

  submitBtn(e) { //点击提交

    console.log(this.data.userName)
    let that = this

    this.nameBlur() //提交时校验
    this.phoneBlur()

    // const pages = getCurrentPages()
    // const prevPage = pages[pages.length - 2] // 上一页
    // if (prevPage && prevPage.data.type == 'addressList') { //判断上一页是否是付款页
    //   console.log(prevPage)
    //   prevPage.data.getAddress.push()
    // }


    if (this.data.nameIstrue == '' && this.data.phoneIstrue == '' && this.data.region != [] && this.data.region[0] != '请选择所在省市区' && this.data.address != '') {

      wx.showModal({
        title: '保存收货地址',
        content: '是否保存收货地址？',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            let isSame = true
            let addressStorage = wx.getStorageSync('addressList')


            for (let i in addressStorage) { //遍历本地缓存
              console.log(that.data.userName == addressStorage[i].contact, that.data.phone == addressStorage[i].mobile, that.data.region[0] == addressStorage[i].provinceId, that.data.region[1] == addressStorage[i].cityId, that.data.region[2] == addressStorage[i].townId, that.data.address == addressStorage[i].address)

              if (that.data.userName == addressStorage[i].contact && that.data.phone == addressStorage[i].mobile && that.data.region[0] == addressStorage[i].provinceId && that.data.region[1] == addressStorage[i].cityId && that.data.region[2] == addressStorage[i].townId && that.data.address == addressStorage[i].address) { //对比是否有相同数据
                isSame = false
              }
            }
            console.log('有无相同数据', isSame)
            if (isSame) { //无相同数据
              wx.request({
                url: 'http://192.168.2.106:8080/updateaddress.do',
                method: 'POST',
                dataType: 'json',
                data: {
                  id: that.data.addressId,
                  userId: that.data.userId,
                  openId: wx.getStorageSync('openId'),
                  provinceId: that.data.region[0],
                  cityId: that.data.region[1],
                  townId: that.data.region[2],
                  mobile: that.data.phone,
                  address: that.data.address,
                  contact: that.data.userName,
                  isDefault: that.data.checked,
                  createData: new Date().getTime(),
                  postalCode: that.data.post,
                },
                header: {
                  'content-type': 'application/json;charset=utf-8'
                },
                success(res) {
                  console.log(res)
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000,
                    success(res) {
                      setTimeout(function() {
                        wx.navigateBack({
                          delta: 1
                        })
                      }, 2000)
                    }
                  })
                },
                fail(res) {
                  console.log(res)
                }
              })
            } else {
              wx.showToast({
                title: '不能添加重复地址',
                duration: 2000
              })
            }
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else { //提交验证失败
      console.log('验证错误')
      wx.showToast({
        title: '请填写正确的信息',
        icon: 'none',
        duration: 2000
      })
    }
  },
  delBtn(e) { //是否删除地址
    let that = this
    wx.showModal({
      title: '删除收货地址',
      content: '是否删除收货地址？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: 'http://192.168.2.106:8080/deleteaddress.do',
            method: 'GET',
            dataType: 'json',
            data: {
              addressiId: that.data.addressId,

            },
            header: {
              'content-type': 'application/json;charset=utf-8'
            },
            success(res) {
              console.log(res)
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000,
                success(res) {
                  setTimeout(function() {
                    wx.navigateBack({
                      delta: 1
                    })
                  }, 2000)
                }
              })
            },
            fail(res) {
              console.log(res)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)

    //传来的参数转化为数据
    if (options.Msg) {

      let res = JSON.parse(options.Msg)
      this.setData({
        addressMsg: JSON.parse(options.Msg),

      })
      // console.log(this.data.addressMsg.province.trim().split(" "))
      this.setData({
        userName: this.data.addressMsg.contact,
        phone: this.data.addressMsg.mobile,
        region: [this.data.addressMsg.provinceId, this.data.addressMsg.cityId, this.data.addressMsg.townId], //地址切割为数组
        address: this.data.addressMsg.address,
        post: this.data.addressMsg.postalCode,
        checked: this.data.addressMsg.isDefault,
        addressId: this.data.addressMsg.id,
        userId: this.data.addressMsg.userId,
      })

    } else {
      // wx.getLocation({
      //   type: 'wgs84',
      //   success(res) {
      //     console.log(res)
      //   }
      // })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})